package com.cms.controllers.admin;

import com.cms.common.aop.permission.PermissionCheck;
import com.cms.common.model.entity.AdminUser;
import com.cms.common.model.entity.UploadFile;
import com.cms.common.model.services.AdminUserService;
import com.cms.common.model.services.UploadFileService;
import com.cms.common.model.vo.ResponseResult;
import com.cms.controllers.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/admin/account")
public class AccountController extends BaseController {

    @Autowired
    AdminUserService adminUserService;
    @Autowired
    UploadFileService uploadFileService;

    @GetMapping("")
    @PermissionCheck(name = "个人信息", typeName = "个人信息")
    public String index(Model viewModel) {
        viewModel.addAttribute("adminUser", request.getAttribute("adminUser"));
        return "admin/account/index";
    }


    @PutMapping("/update")
    @ResponseBody
    @PermissionCheck(name = "修改密码和头像", typeName = "个人信息")
    public ResponseResult update(@RequestParam("name") String name,@RequestParam(value = "password", defaultValue = "") String password, @RequestParam("photo_md5") String photo_md5) {

        AdminUser adminUser = (AdminUser) request.getAttribute("adminUser");
        if (!password.isEmpty()) {
            adminUser.setPassword(adminUserService.encodePwd(adminUser.getUsername(), password, adminUser.getSalt()));
        }
        UploadFile photo = uploadFileService.findByMd5(photo_md5);
        if (photo != null) {
            adminUser.setPhoto(photo);
        }
        adminUser.setName(name);
        adminUser = adminUserService.insertAdminUser(adminUser);
        return ResponseResult.success(adminUser);
    }
}
